<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            height:3000px;
        }
        #back{
            height:100px;
            width:100px;
            background-color: red;
            position: fixed;
            bottom:30px;
            right:30px;
            z-index:-10;
            opacity: 0;
            transition: all 1s;
        }
    </style>
</head>
<body>
    <h1>1111</h1>
    <div id="back">返回顶部</div>
    <script>
        var html=document.documentElement||document.body;
        var timer=null,step=10;
        //返回顶部按钮（back）点击（onclick）
        back.onclick=function(){
            if(timer==null){
                timer=setInterval(()=>{
                    var t=html.scrollTop;
                    t-=step;
                    if(t<=0){
                        html.scrollTop=0;
                        clearInterval(timer);
                        timer=null;
                        return;
                    }
                    html.scrollTop=t;
                },10)
            }
        }

        //视口（document window）滚动（onscroll）
         document.onscroll=function(){
            if(html.scrollTop>100){
                back.style.opacity=1;
                back.style.zIndex=10;
            }else{
                back.style.opacity=0;
                back.style.zIndex=-10; 
            }
         }
    </script>
</body>
</html>